<!--
 * @Date: 2020-08-13 09:28:27
 * @LastEditors: leehave
 * @LastEditTime: 2020-08-21 10:51:37
-->
<template>
  <div class="bind-phone">
    <van-form @submit="submitPhone">
      <van-cell-group title="请绑定您的手机号" class="cell-top">
      <van-field
        v-model="tel"
        type="tel"
        name="tel"
        label="手机号"
        placeholder="手机号"
        trigger="onChange"
        @input="onPhoneChange"
        :rules="[{ required: true, message: msgFun, validator:handleValidate }]"
      />
      <van-field
        v-model="code"
        type="number"
        name="code"
        label=""
        placeholder="验证码"
        trigger="onChange"
        :rules="[{ required: true }]"
      >
        <template #button>
          <van-button size="small" round color="#4ECE40" :disabled="isSmsSend" @click="handleSendMsg">{{ sendBtnText }}</van-button>
        </template>
      </van-field>
      <div style="padding: 20px">
        <van-button  block color="#4ECE40" native-type="submit">确认绑定</van-button>
      </div>
      </van-cell-group>
    </van-form>
  </div>
</template>

<script>
import {isPhoneNum} from '@/utils/validate.js';
import { bindUserPhone,sendMessageService } from '@/service/user';
import { mapGetters } from 'vuex'
import {
  loadToken
} from '@/utils/cache'
export default {
  data() {
    return {
      tel: '',
      code: '',
      disabled: false,
        // 是否已经发送了验证码
      isSmsSend: false,
      // 文本
      sendBtnText: '点击发送验证码',
      // 计时器对象
      timer: null,
      // 倒数60秒
      counter: 60
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    let token = loadToken()
    if(!token){
    }else{
      this.$router.replace({
        path: '/home/index'
      })
    }
  },
  mounted() {},
  watch: {
    
  },
  methods: {
    onPhoneChange () {
      this.reset()
    },
    async handleSendMsg(){
      let result = await sendMessageService({
        tel: this.tel,
        type: 'forgetPassword'
      })
      if(result.status != 200){
        this.$toast(result.message)
      }else{
        // this.code = result.data
        let resultStr = JSON.parse(result.data);
        if(resultStr.SendStatusSet[0].Code == 'Ok'){
          this.disabled = true
          this.isSmsSend = true
          this.countDown()
          this.$toast('发送成功')
        }
      }
    },
    handleValidate(value,rule){
      if(!isPhoneNum(value)){
        return false
      }
    },
    /**
     * 重置倒计时
     */
    reset () {
      // 重置按钮可用
      this.isSmsSend = false
      // 重置文本内容
      this.sendBtnText = '点击发送验证码'
      if (this.timer) {
        // 存在计时器对象，则清除
        clearInterval(this.timer)
        // 重置秒数，防止下次混乱
        this.counter = 60
        // 计时器对象重置为空
        this.timer = null
      }
    },
    /**
       * 倒计时
       */
    countDown () {
      // 将setInterval()方法赋值给前面定义的timer计时器对象，等用clearInterval()方法时方便清空这个计时器对象
      this.timer = setInterval(() => {
        // 替换文本，用es6里面的``这个来创建字符串模板，让秒实时改变
        this.sendBtnText = `(${this.counter}秒)后重新发送`
        this.counter--
        if (this.counter < 0) {
          // 当计时小于零时，取消该计时器
          clearInterval(this.timer)
          this.reset()
        }
        
      }, 1000)
    },
    msgFun(value,rule){
      if(value == ''){
        return '请填写手机号'
      } else if(!isPhoneNum(value)){
        return '手机号格式错误'
      }
    },
    handleComparePhone(){
      if(this.tel == ''){
        this.$toast('请输入手机号')
        return
      }
     
    },
    async submitPhone(values){
      
      if(this.tel == ''){
        this.$toast('请填写手机号')
        return
      }
      
      let params = {
        code: this.code,
        tel: this.tel
      }
      bindUserPhone(params).then(res => {
        if(res.status == '200'){
          this.$store.dispatch('user/updateUserInfo') 
          this.$router.replace({
            path: '/home'
          })
        }else{
          this.$store.dispatch('user/updateUserInfo') 
          this.$store.dispatch('user/fedLogOut') 
          
        }
      })

      console.log(values)
    }
  },
  components: {},
};
</script>

<style lang="less">
.van-cell-group__title{
  margin-top: 20px;
}
</style>
